<template>
    <div class="wallet-recharge">
        <button @click="openRechargeDialog()">Add funds</button>


        <UxDialog :visible="!!recharge" :canClose="false" @close="recharge = false">



            <div class="wallet-recharge-dialog" v-if="tab == 'bank'">

                <div class="wallet-recharge-close" @click="recharge = false"></div>


                <h2>Bank transfer information</h2>


                <div class="wallet-recharge-region">
                    <strong>Country/Region:</strong>
                    <span>{{ areaNotify.name }}</span>

                    <UxToolTip placement="top">
                        <svg-icon name="notify2" />
                        <div slot="content" class="wallet-recharge-notify" v-text="areaNotify.notify"></div>
                    </UxToolTip>
                </div>

                <div class="wallet-recharge-transfer" v-if="config.bank_country_code == 'US'">
                    <span>Transfer Methods:</span>
                    <UxSelect v-model="form.recharge_rich_id" :options="areaOptions" :clearable="false" />
                    <em v-if="bankName == 'USD-ACH'">Funds arrive in 1-3 business days. Lower fees. Single transfer
                        limit: USD 25,000</em>
                    <em v-if="bankName == 'USD-Fedwire'">Funds arrive within 1 business day. Higher fees. No transfer
                        limit.</em>


                </div>

                <div class="wallet-recharge-bank" v-html="bankContent"></div>

                <p>
                    <strong>Notes</strong>
                    <span>1. Please submit your transfer details after making a payment. We cannot process your transfer
                        without it.</span>
                    <span>2. Be aware that repeated transfer of the same amount in a short period may trigger bank
                        security review.</span>

                    <span>3. Get a 2% cashback on transfers (e.g., transfer 1000 USD, receive 1020 USD in your POD
                        wallet).</span>

                </p>
                <fieldset>
                    <button @click="tab = 'apply'" type="primary">Submit transfer details</button>
                </fieldset>
            </div>


            <div class="wallet-recharge-apply" v-if="tab == 'apply'">

                <div class="wallet-recharge-back" @click="tab = 'bank'"></div>


                <h2>Submit transfer details</h2>

                <div class="wallet-recharge-user">
                    <div class="wallet-recharge-user-cache" v-if="form.from_cache">
                        <p>
                            <span>Cardholder name:</span>
                            <strong v-text="form.cardholder"></strong>
                        </p>
                        <p>
                            <span>Phone:</span>
                            <strong v-text="form.phone"></strong>
                        </p>
                        <svg-icon name="dialog-close-medium" @click.native="setHolder()" />
                    </div>

                    <div class="wallet-recharge-user-input" v-else>

                        <label name="Cardholder name" :class="{ error: notify.name }">
                            <input type="text" v-model="form.cardholder" @blur="checkNotify('name')" />
                            <em v-if="notify.name" v-text="notify.name"></em>
                            <span v-else>Please ensure that the name you provide is accurate.</span>
                        </label>

                        <label name="Phone" :class="{ error: notify.phone }">
                            <input type="text" v-model="form.phone" @blur="checkNotify('phone')" />
                            <em v-if="notify.phone" v-text="notify.phone"></em>
                        </label>

                        <a @click="setHolder(form)" v-if="form.cardholder && form.phone">Save as default</a>
                    </div>
                </div>

                <div class="wallet-recharge-transfer">

                    <div class="wallet-recharge-amount">

                        <label name="Transfer amount" :class="{ error: notify.amount }">
                            <span>{{ countryName }}</span>
                            <input type="text" v-model="form.transfer_amount" @input="onInput($event)"
                                   @blur="form.transfer_amount = amountFormat; checkNotify('amount')" />
                        </label>

                        <div class="wallet-recharge-convert" v-if="config.bank_country_code != 'US'">
                            <strong>Convert to USD</strong>
                            <span>({{ countryName }} : USD = 1 :
                                {{ (1 / form.current_exchange_rate).toFixed(5) }})</span>
                            <em>{{ (price.rate / 100).toFixed(2) }}</em>
                        </div>

                        <div class="wallet-recharge-cashback">
                            <span>{{ config.discount }}% Cashback </span>
                            <strong v-text="'+ ' + (price.discount / 100).toFixed(2)"></strong>
                        </div>

                        <div class="wallet-recharge-total">
                            <strong>Deposit amount: </strong>
                            <span>USD </span>
                            <em v-text="(price.total / 100).toFixed(2)"></em>
                        </div>
                    </div>

                    <div class="wallet-recharge-screenshot" :class="{ error: notify.screenshot }">
                        <span>Transfer screenshot</span>
                        <UserUploaderCard :folder="folder" v-model="form.transfer_screenshot"
                                          @change="checkNotify('screenshot')" />
                    </div>
                </div>

                <fieldset>
                    <!-- <button @click="tab = 'bank'">Cancel</button> -->
                    <button @click="doSubmit()" type="primary" :class="{ disabled: submitDisabled }">Submit</button>
                </fieldset>
            </div>



            <UxLoading2 :loading="loading" />
        </UxDialog>

    </div>
</template>
<script>
import Md5 from "js-md5";
import { mapGetters, mapState } from "vuex";
export default {
    props: {
        config: { type: Object, default: () => ({}) },
    },
    data () {
        return {
            recharge: false,
            loading: false,
            banks: [],
            tab: 'bank',
            folder: '',
            form: {
                recharge_rich_id: '',
                cardholder: '',
                phone: '',
                transfer_amount: '',
                recharge_amount: '',
                transfer_screenshot: '',
                current_exchange_rate: 1,
                rebate_points: 2,
                from_cache: false,
            },
            notify: {
                name: '',
                phone: '',
                amount: '',
                screenshot: '',
            }
        };
    },

    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),

        countryName () {
            return { 'US': 'USD', 'CA': 'CAD', 'EU': 'EUR', 'UK': 'GBP' }[this.config.bank_country_code]
        },

        areaNotify () {

            const obj = {
                'US': { name: 'United States', notify: 'Please note that bank transfer are only possible with US-issued bank cards and USD.' },
                'EU': { name: 'European Union countries', notify: 'Please note that bank transfer are only possible with EU-issued bank cards and EUR.' },
                'CA': { name: 'Canada', notify: 'Please note that bank transfer are only possible with Canadian-issued bank cards and CAD.' },
                'UK': { name: 'United Kingdom', notify: 'Please note that bank transfer are only possible with UK-issued bank cards and GBP.' },
            }
            return obj[this.config.bank_country_code] || {}
        },

        areaOptions () {
            return this.banks.map(i => ({ label: i.name.replace(/^[^-]+-/, ''), value: i.id, id: i.id }))
        },

        bankName () {
            return (this.banks.find(i => i.id == this.form.recharge_rich_id) || {}).name
        },

        bankContent () {

            const content = (this.banks.find(i => i.id == this.form.recharge_rich_id) || {}).content || ''
            const res = (content.match(/<p>[\w\W]+?<\/p>/g) || []).map(line => {
                const arr = line.replace(/<\/?p>/g, '').split(/\s?[:：]\s?/g);
                if (arr.length == 1) {
                    return line
                } else {
                    return `<p><span>${arr[0]} :</span><strong>${arr.slice(1).join('')}</strong></p>`
                }
            }).join('')

            return res
        },

        cardholderFormat () {
            return String(this.form.cardholder).replace(/(^\s*)|(\s*$)/g, "");
        },

        phoneFormat () {
            return String(this.form.phone).replace(/(^\s*)|(\s*$)/g, "");
        },
        amountFormat () {
            return parseFloat(this.form.transfer_amount) || 0
        },

        submitDisabled () {
            return !(this.cardholderFormat && this.phoneFormat && this.amountFormat && this.form.transfer_screenshot)
        },

        // 价格
        price () {
            // 转美分
            const original = Math.round(100 * this.amountFormat)
            const price_rate = Math.ceil(original / this.form.current_exchange_rate)
            const price_discount = Math.ceil(price_rate * this.config.discount / 100)
            const price_total = price_rate + price_discount
            return {
                original: original,
                rate: price_rate,
                discount: price_discount,
                total: price_total,
            }
        }
    },
    methods: {

        // 获取可用的银行
        async getBankArea () {

            if (this.banks.length == 0) {
                const res = await this.$http('Wallet.getBankArea', { bank_country_code: this.config.bank_country_code })
                this.banks = res.data || []
                this.form.recharge_rich_id = (this.banks[0] || {}).id || '';
            } else {
                // 默认id
            }

        },

        // 获取汇率
        async getRate () {

            if (this.config.bank_country_code == 'US') {
                this.form.current_exchange_rate = 1
            } else {
                const res = await this.$http('Resource.getCurrency/' + this.countryName)
                this.form.current_exchange_rate = (res.data || {}).rate || 1
            }
        },

        onInput (event) {
            const reg = /[^0-9.]/g;
            const precision = 2;
            let value = event.target.value || '';

            value = value.replace(reg, ''); // 删除数字和.以外的内容
            value = value.replace(/\.+/, '.'); // 连续多个点: 1...
            value = (value.match(/\./g) || []).length > 1 ? value.split('.').slice(0, 2).join('.') : value; // 间隔多个点: 1.2.3.
            value = /^\.+/.test(value) ? value.replace(/^\.+/, '') : value; // 纯点的情况:...
            value = value.replace(/\.\d+/, s => s.substring(0, precision + 1)); // 处理后面好多个0
            value = value.replace(/^0+(\d)/, '$1'); // 处理前面好多个0的情况

            value = value.split('.').map((s, i) => i == 0 ? s.substring(0, 5) : s).join('.')

            event.target.value = value;
            this.form.transfer_amount = value;
        },

        checkNotify (type) {
            const list = type ? [type] : ['name', 'phone', 'amount', 'screenshot']
            list.indexOf('name') >= 0 && (this.notify.name = this.cardholderFormat ? '' : 'Please enter your cardholder name')
            list.indexOf('phone') >= 0 && (this.notify.phone = this.phoneFormat ? '' : 'Please enter your phone')
            list.indexOf('amount') >= 0 && (this.notify.amount = this.amountFormat ? '' : 'Please enter transfer amount')
            list.indexOf('screenshot') >= 0 && (this.notify.screenshot = this.form.transfer_screenshot ? '' : 'Please upload screenshot')
        },

        // 修改
        setHolder (opt) {

            if (opt && this.cardholderFormat && this.phoneFormat) {
                this.$emit('update-user', { cardholder: this.cardholderFormat, phone: this.phoneFormat })
                this.form.from_cache = true;
            } else {
                this.$emit('update-user', { cardholder: '', phone: '' })
                this.form.cardholder = '';
                this.form.phone = '';
                this.form.from_cache = false;
            }
        },


        // 打开对话框
        openRechargeDialog () {
            this.recharge = true;
            this.loading = true;
            this.tab = 'bank';
            this.folder = `/wallet/${Md5(this.userInfo.email || '')}/voucher1`

            if (this.config.cardholder && this.config.phone) {
                this.form.from_cache = true;
                this.form.cardholder = this.config.cardholder;
                this.form.phone = this.config.phone;
            } else {
                this.form.from_cache = false;
                this.form.cardholder = '';
                this.form.phone = '';
            }

            this.notify.name = '';
            this.notify.phone = '';
            this.notify.amount = '';
            this.notify.screenshot = '';

            this.form.transfer_amount = '';
            this.form.recharge_amount = '';
            this.form.transfer_screenshot = '';
            this.form.rebate_points = this.config.discount


            Promise.all([this.getBankArea(), this.getRate()]).then(res => this.loading = false)
        },

        // 提交转账信息
        doSubmit () {

            if (this.submitDisabled) {
                this.checkNotify()
            } else {
                // 充值折扣
                // 请求体
                const request = {
                    recharge_rich_id: this.form.recharge_rich_id,
                    cardholder: this.cardholderFormat,
                    phone: this.phoneFormat,
                    transfer_amount: this.price.original,
                    recharge_amount: this.price.total,
                    transfer_screenshot: this.form.transfer_screenshot,
                    current_exchange_rate: this.form.current_exchange_rate,
                    rebate_points: this.config.discount,
                }

                // 发起请求
                this.loading = true;
                this.$http('Wallet.putTxRecharge', request).then(res => {
                    if (res.code === 0) {
                        this.$uxMessage.success("Successfully submit.");
                        this.loading = false;
                        this.recharge = false;
                        this.$emit('reload')
                    } else {
                        this.loading = false
                        this.$uxMessage.error(res.msg);
                    }

                });

            }


        }
    },
    created () {

    },
};
</script>
<style lang="scss" scoped>
.wallet-recharge {

    &>button {
        width: 108px;
        height: 36px;
        background-color: #fff;
    }
}



.wallet-recharge-close {
    position: absolute;
    width: 26px;
    height: 26px;
    top: 12px;
    right: 12px;
    border-radius: 6px;
    background-size: 26px 26px;
    background-image: url(@/assets/images/designer/dialog-close.png);
    background-position: center center;
    background-repeat: no-repeat;
    cursor: pointer;

    &:hover {
        background-color: rgba($color: #ff0000, $alpha: 0.2);
    }
}


.wallet-recharge-dialog {
    width: 816px;
    box-sizing: border-box;
    padding: 40px;

    &>h2 {
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        font-size: 24px;
        color: #000000;
        line-height: 28px;
        text-align: center;
    }

    &>p {
        font-family: Roboto, Roboto;
        font-weight: 400;
        font-size: 14px;
        color: #292929;
        line-height: 22px;
        margin-top: 24px;
    }

    .wallet-recharge-region {
        margin-top: 34px;
        font-family: Roboto, Roboto;
        font-weight: 500;
        font-size: 14px;
        color: #555555;
        line-height: 16px;
        display: flex;
        align-items: center;

        strong {
            font-family: Roboto-Medium, Roboto;
            margin-right: 6px;
            color: #000000;
            font-weight: 400;
        }

        .tooltip {
            margin-left: 4px;
        }

        .wallet-recharge-notify {
            width: 264px;
        }
    }

    .wallet-recharge-transfer {
        display: flex;
        font-family: Roboto, Roboto;
        font-weight: 400;
        font-size: 14px;
        color: #555555;
        line-height: 32px;
        margin-top: 12px;

        span {
            font-family: Roboto-Medium, Roboto;
            white-space: nowrap;
            color: #000;
            font-weight: 400;
        }

        .form-select {
            width: 102px;
            height: 32px;
            margin-left: 6px;
            margin-right: 10px;
        }

        em {
            white-space: nowrap;
        }
    }

    .wallet-recharge-bank {
        margin-top: 24px;
        background: #F7F7F7;
        border-radius: 8px;
        border: 1px solid #F0F0F0;
        padding: 20px;
        font-family: Roboto, Roboto;
        font-weight: 400;
        font-size: 14px;
        color: #000000;
        line-height: 28px;
        min-height: 236px;
        box-sizing: border-box;


        &::v-deep p {
            display: flex;
        }

        &::v-deep span {
            width: 150px;
            text-align: right;
        }

        &::v-deep strong {
            margin-left: 10px;
            font-weight: normal;
        }

    }

    p {
        margin-top: 16px;
        display: flex;
        flex-direction: column;

        strong {
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            font-size: 14px;
            color: #292929;
            line-height: 22px;
        }

        span {
            font-family: Roboto, Roboto;
            font-weight: 400;
            font-size: 14px;
            color: #292929;
            line-height: 22px;
        }
    }

    &>fieldset {
        margin: 32px 0 0;
        text-align: center;

        button {
            width: 240px;
            height: 40px;
        }
    }
}


.wallet-recharge-apply {
    padding: 40px;
    width: 492px;
    box-sizing: border-box;
    position: relative;

    .wallet-recharge-back {
        position: absolute;
        width: 26px;
        height: 26px;
        top: 12px;
        left: 12px;
        border-radius: 6px;
        background-size: 26px 26px;
        background-image: url(@/assets/images/designer/dialog-back.png);
        background-position: center center;
        background-repeat: no-repeat;
        cursor: pointer;

        &:hover {
            background-color: #ebebeb;
        }
    }



    &>h2 {
        margin-top: 16px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        font-size: 22px;
        color: #000000;
        line-height: 28px;
        text-align: center;
    }


    .wallet-recharge-user {
        position: relative;
        margin-top: 40px;
        display: flex;
        flex-direction: column;
        height: 144px;
        border-bottom: 1px dashed #CCCCCC;
    }

    .wallet-recharge-user-cache {
        height: 114px;
        background: #F7F7F7;
        border-radius: 8px;
        padding: 32px 26px;
        box-sizing: border-box;

        p {
            font-family: Roboto, Roboto;
            font-weight: 500;
            font-size: 14px;
            color: #000000;
            line-height: 16px;
            text-align: left;
            display: flex;

            span {
                width: 112px;
                white-space: nowrap;
                margin-right: 10px;
                color: #555555;
                text-align: right;
            }

            strong {
                font-weight: normal;
                color: #000;
                font-weight: 400;
            }

            &+p {
                margin-top: 18px;
            }
        }

        svg {
            position: absolute;
            right: 4px;
            top: 4px;
            width: 14px;
            height: 14px;
            box-sizing: border-box;
            padding: 3px;
            cursor: pointer;

            &:hover {
                background-color: #eee;
                color: #ea4c89;
            }
        }
    }

    .wallet-recharge-user-input {
        display: flex;
        padding-top: 24px;
        position: relative;
        flex: 1;

        label {
            display: flex;
            position: relative;
            width: 140px;
            height: 36px;

            &:first-child {
                width: 260px;
                margin-right: 12px;
            }

            &::before {
                content: attr(name);
                position: absolute;
                left: 0;
                bottom: 100%;
                margin-bottom: 8px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #000000;
                line-height: 16px;
            }

            &>span {
                position: absolute;
                left: 0;
                top: 100%;
                margin-top: 4px;
            }

            &>em {
                position: absolute;
                left: 0;
                top: 100%;
                margin-top: 4px;
                color: #C62828;
            }

            input {
                height: 36px;
            }

            &.error {
                input {
                    border-color: #C62828;
                }
            }
        }

        &>a {
            position: absolute;
            left: 0;
            bottom: 18px;
            font-family: Roboto, Roboto;
            font-weight: 400;
            font-size: 14px;
            color: #087196;
            line-height: 16px;
            text-decoration: underline;
            cursor: pointer;

            &:hover {
                text-decoration: none;
                color: #287e9c;
            }
        }
    }



    .wallet-recharge-transfer {
        display: flex;
        margin-top: 40px;
    }

    .wallet-recharge-amount {
        width: 236px;
        margin-right: 36px;

        label {
            position: relative;
            margin-top: 24px;
            display: block;

            &::before {
                content: attr(name);
                position: absolute;
                top: -24px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #000000;
                line-height: 16px;
            }

            input {
                height: 36px;
                padding-left: 72px;
            }

            span {
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 60px;
                height: 34px;
                line-height: 34px;
                text-align: center;
                border-right: 1px solid #E6E6E6;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #555555;
            }

            &.error input {
                border-color: #C62828;
            }
        }

        .wallet-recharge-convert {
            position: relative;
            margin-top: 8px;
            height: 32px;

            strong {
                display: block;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #292929;
                line-height: 16px;
            }

            span {
                display: block;
                font-family: Roboto, Roboto;
                font-weight: 500;
                font-size: 12px;
                color: #292929;
                line-height: 16px;
            }

            em {
                position: absolute;
                right: 0;
                top: 0;
                font-family: Roboto, Roboto;
                font-weight: 400;
                font-size: 14px;
                color: #292929;
                line-height: 16px;
            }


            &+.wallet-recharge-cashback {
                margin-top: 8px;
                height: 16px;
            }

        }

        .wallet-recharge-cashback {
            margin-top: 10px;
            height: 56px;
            display: flex;
            align-items: center;

            span {
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #292929;
                line-height: 16px;
                flex: 1;
            }

            strong {
                font-family: Roboto, Roboto;
                font-weight: 400;
                font-size: 14px;
                color: #292929;
                line-height: 16px;
            }
        }

        .wallet-recharge-total {
            margin-top: 10px;
            border-top: 1px dashed #CCCCCC;
            display: flex;
            padding-top: 7px;

            strong {
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #292929;
                line-height: 20px;
                flex: 1;
            }

            span {
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 14px;
                color: #292929;
                line-height: 16px;
                margin-top: 4px;
                margin-right: 4px;
            }

            em {
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                font-size: 20px;
                color: #000000;
                line-height: 20px;
            }
        }
    }

    .wallet-recharge-screenshot {
        flex: 1;

        span {
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            font-size: 14px;
            color: #000000;
            line-height: 16px;
        }

        .uploader {
            margin-top: 10px;
            width: 100%;
        }

        &.error::v-deep .uploader {

            .uploading,
            .waiting,
            .empty {
                border-color: #C62828;

            }
        }
    }


    &>fieldset {
        display: flex;
        margin-top: 50px;
        justify-content: center;

        button {
            width: 240px;
            height: 40px;
            margin: 0 4px;
        }
    }
}
</style>
